package com.server.libs.EmailCode;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class ForgetPasswordEmailCode {
    @Autowired
    StringRedisTemplate redis;

    final private String suffix = "_email_code_forgetPassword";

    public String create(String email){
        email += suffix;
        String code = String.format("%06d",(int)(Math.random()* (999999)+1));//产生(0,999999]之间的随机数
        redis.opsForValue().set(email,code,600, TimeUnit.SECONDS);
        return code;
    }

    public boolean check(String email,String code){
        email += suffix;
        if(!code.equalsIgnoreCase(redis.opsForValue().get(email))){
            return false;
        }
        redis.delete(email);
        return true;
    }

    public boolean isSend(String email){
        email += suffix;
        return (getExpire(email) >= 600-60);
    }

    public void del(String email){
        email += suffix;
        redis.delete(email);
    }

    public Long getExpire(String key){
        Long expireTime = redis.getExpire(key, TimeUnit.SECONDS);
        if (expireTime == null) expireTime = -1L;
        return expireTime;
    }
}
